﻿var UserDetail = function () {
    // 页面全局
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "positionClass": "toast-top-center",
        "onclick": null,
        "showDuration": "500",
        "hideDuration": "500",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };

    // 初始化更新表单控件
    var initUpdateUserForm = function () {
        var updateForm = $("#updateForm");
        var btnUpdateUser = $("#btnUpdateUser");
        var btnUpdateUserCancel = $("#btnUpdateUserCancel");

        var validator = updateForm.validate({
            onsubmit: false,
            rules: {
                firstname: {
                    required: true
                },
                lastname: {
                    required: true
                },
                phone: {
                    maxlength: 11
                },
                qq: {
                    digits: true,
                    minlength: 5,
                    maxlength: 11
                },
                email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                firstname: {
                    required: "姓氏必须填写"
                },
                lastname: {
                    required: "名字必须填写"
                },
                phone: {
                    maxlength: "电话号码长度超过11个字符，将被截断"
                },
                qq: {
                    digits: "请输入正确的QQ号",
                    minlength: "请输入正确的QQ号",
                    maxlength: "请输入正确的QQ号"
                },
                email: {
                    required: "Email必须提供",
                    email: "非法的Email格式"
                }
            },
            errorPlacement: function (error, element) {
                error.removeClass().addClass("text-danger ml-20");
                var _container = element.prev();
                _container.empty();
                error.appendTo(_container);
                element.parent().removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                label.empty().append('<i class="fa fa-check"></i>');
                label.removeClass().addClass("text-success ml-20");
                $(element).parent().removeClass("has-error").addClass("has-success");
            }
        });

        btnUpdateUserCancel.bind("click", function () {
            updateForm[0].reset();

            updateForm.find("input[type='radio'], input[type='checkbox']").each(function () {
                var radio = $(this);
                if (this.checked) {
                    radio
                        .parent().addClass("checked");
                } else {
                    radio
                        .parent().removeClass();
                }
            });
        });
        btnUpdateUser.init = function () {
            this.empty().html("更新");
            this.removeAttr("disabled");
        };
        btnUpdateUser.message = function (response) {
            if (response.Result) {
                var Fields = response.Data;
                var fullName = Fields.CNName ? Fields.FirstName + Fields.LastName : Fields.LastName + ' ' + Fields.FirstName;
                tr = $("#tr_" + Fields.UID);

                tr.find("td[data-field]").each(function () {
                    var td = $(this);
                    switch (td.attr("data-field")) {
                        case "groups":
                            td.html(Fields.Groups);
                            break;
                        case "fullname":
                            td.html(fullName);
                            break;
                        case "email":
                            td.empty();
                            if (Fields.Email) {
                                td.append('<a href="mailto:' + Fields.Email + '">' + Fields.Email + '</a>')
                            }
                            break;
                        case "phone":
                            td.html(Fields.Phone);
                            break;
                        case "qq":
                            td.html(Fields.QQ);
                            break;
                    }
                });

                $("#profile_email").html(Fields.Email);
                if (Fields.Email) $("#profile_email").attr("href", "mailto:" + Fields.Email);
                $("#profile_phone").html(Fields.Phone);
                $("#profile_qq").html(Fields.QQ);
                $("#profile_fullname").html("关于 " + fullName);
                $("#profile_primary_fullname").html(fullName);
                $("#profile_memo").html(Fields.Memo ? Fields.Memo : "什么信息都没有留下");

                toastr["success"](response.Message, "更新用户信息");
            } else {
                toastr["error"](response.Message, "更新用户信息");
            }
        };
        btnUpdateUser.bind("click", function () {
            if (!validator.valid()) {
                toastr["warning"]("表单验证不通过，请仔细核对后再尝试一次", "更新用户信息");
                return;
            }

            btnUpdateUser.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在更新');
            btnUpdateUser.attr("disabled", "disabled");

            $.ajax({
                url: updateForm.attr("action"),
                data: updateForm.serializeArray(),
                type: "POST",
                success: function (Response) {
                    btnUpdateUser.message(Response);
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "创建新用户");
                },
                complete: function () {
                    btnUpdateUser.init();
                }
            });
        });
    };

    // 初始化头像上传控件
    var initAvatarUploadForm = function () {
        var avatar = $("#fileAvatar");
        var btnUpload = $("#btnUpload");
        var btnCancelUpload = $("#btnCancelUpload");
        var jQueryForm = $("#avatarForm");
        var form = jQueryForm[0];
        var fileuoloadData = null;

        avatar.fileupload({
            dataType: "json",
            url: jQueryForm.attr("action"),
            autoUpload: false,
            maxFileSize: 1000000,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            add: function (e, data) {
                fileuoloadData = data;
            },
            done: function (e, data) {
                btnUpload.message(data.result);
                btnUpload.init();
            },
            fail: function (e, data) {
                toastr["error"]("您没有权限或是程序碰到问题没有正确执行！", "更新用户头像");
                btnUpload.init();
            }
        });

        // 大图预览
        var upPreviewLarge = avatar.uploadImagePreview({
            previewContainerID: 'avatarLargePreview',
            imgWidth: 125
        });
        // 小图预览
        var upPreviewSmall = avatar.uploadImagePreview({
            previewContainerID: 'avatarSmallPreview',
            imgWidth: 30
        });

        btnCancelUpload.bind("click", function () {
            fileuoloadData = null;
            upPreviewLarge.reset();
            upPreviewSmall.reset();
        });
        btnUpload.init = function () {
            this.empty().html("更新头像");
            this.removeAttr("disabled");
        }
        btnUpload.message = function (response) {
            if (response.Result) {
                var picUrl = response.Data.PicUrl;
                var uid = response.Data.UID;
                var smallPicUrl = picUrl + "small.png?" + Math.random();
                $("#profile_userpic > img").attr("src", picUrl + "large.png?" + Math.random());
                $("#tr_" + uid + " img[data-field='avatar']").attr("src", smallPicUrl);
                $("#user_avatar").attr("src", smallPicUrl);
                toastr["success"](response.Message, "更新用户头像");
            } else {
                toastr["error"](response.Message, "更新用户头像");
            }
        }
        btnUpload.bind("click", function () {
            if (fileuoloadData) {
                btnUpload.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在保存');
                btnUpload.attr("disabled", "disabled");
                fileuoloadData.submit();
            } else {
                toastr["warning"]("并未选择要上传的照片！", "更新用户头像");
            }
        });
    };

    // 初始化更新密码表单
    var initUpdatePasswordForm = function () {
        var updatePasswordForm = $("#updatePasswordForm");
        var btnUpdatePWD = $("#btnUpdatePWD");
        var btnCancelUpdatePWD = $("#btnCancelUpdatePWD");

        var validator = updatePasswordForm.validate({
            onsubmit: false,
            rules: {
                currpassword: {
                    required: true
                },
                newpassword: {
                    required: true,
                    minlength: 6
                },
                confirmpassword: {
                    required: true,
                    equalTo: "#newpassword"
                }
            },
            messages: {
                currpassword: {
                    required: "未提供初始密码"
                },
                newpassword: {
                    required: "必须提供新的密码",
                    minlength: "密码至少要6位"
                },
                confirmpassword: {
                    required: "请确认您输入的密码",
                    equalTo: "您输入的密码不一致"
                }
            },
            errorPlacement: function (error, element) {
                error.removeClass().addClass("text-danger ml-20");
                var _container = element.prev();
                _container.empty();
                error.appendTo(_container);
                element.parent().removeClass("has-success").addClass("has-error");
            },
            success: function (label, element) {
                label.empty().append('<i class="fa fa-check"></i>');
                label.removeClass().addClass("text-success ml-20");
                $(element).parent().removeClass("has-error").addClass("has-success");
            }
        });

        btnCancelUpdatePWD.bind("click", function () {
            updatePasswordForm[0].reset();
        });
        btnUpdatePWD.init = function () {
            this.empty().html("更新密码");
            this.removeAttr("disabled");
        };
        btnUpdatePWD.message = function (response) {
            if (response.Result) {
                toastr["success"](response.Message, "更新用户密码");
            } else {
                toastr["error"](response.Message, "更新用户密码");
            }
        };
        btnUpdatePWD.bind("click", function () {
            if (!validator.valid()) {
                toastr["warning"]("表单验证不通过，请仔细核对后再尝试一次", "更新用户密码");
                return;
            }

            btnUpdatePWD.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在更新');
            btnUpdatePWD.attr("disabled", "disabled");

            $.ajax({
                url: updatePasswordForm.attr("action"),
                data: updatePasswordForm.serializeArray(),
                type: "POST",
                success: function (Response) {
                    btnUpdatePWD.message(Response);
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "更新用户密码");
                },
                complete: function () {
                    btnUpdatePWD.init();
                }
            });
        });
    };

    var initUpdatePermissionForm = function () {
        var updatePermissionForm = $("#updatePermissionForm");
        var btnUpdatePermission = $("#btnUpdatePermission");
        var btnCancelUpdatePermission = $("#btnCancelUpdatePermission");


        btnUpdatePermission.init = function () {
            this.empty().html("更新");
            this.removeAttr("disabled");
        };
        btnUpdatePermission.message = function (response) {
            if (response.Result) {
                toastr["success"](response.Message, "更新用户权限");
            } else {
                toastr["error"](response.Message, "更新用户权限");
            }
        };
        btnUpdatePermission.bind("click", function () {
            btnUpdatePermission.empty().append('<i class="fa fa-spinner fa-spin"></i> 正在更新');
            btnUpdatePermission.attr("disabled", "disabled");

            $.ajax({
                url: updatePermissionForm.attr("action"),
                data: updatePermissionForm.serializeArray(),
                type: "POST",
                success: function (Response) {
                    btnUpdatePermission.message(Response);
                },
                error: function () {
                    toastr["error"]("程序碰到问题没有正确执行！", "更新用户权限");
                },
                complete: function () {
                    btnUpdatePermission.init();
                }
            });
        });
    };

    // 初始化菜单配置
    var initUpdateMenuPermissionPanel = function () {
        $("#updateMenuSettingForm")
        .AjaxForm({
            submitButton: {
                selector: "#btnUpdateMenuPermission",
                loadingText: "正在更新"
            },
            resetButton: {
                selector: "#btnCancelUpdateMenuPermission"
            },
            alertTitle: "更新组权限",
            notCompletedResetForm: false
        });
    };

    return {
        init: function () {
            Metronic.initComponents();
            initUpdateUserForm();
            initAvatarUploadForm();
            initUpdatePasswordForm();
            initUpdatePermissionForm();
            initUpdateMenuPermissionPanel();
        },
        initUpdateUserForm: function () {
            initUpdateUserForm();
        },
        initAvatarUploadForm: function () {
            initAvatarUploadForm();
        },
        initUpdatePasswordForm: function () {
            initUpdatePasswordForm();
        }
    }
} ();